1 函数定义
1.1 function 函数名
function name(){//...}
1.2 箭头函数
- 箭头函数没有this
- 箭头函数外层代码的this
1.2.1 function保留this
1. 通过bind方法
let p = {
name: "Aeroxian,
getName: function () {
// 需要改变this指向
// 异步代码
setTimeout(function () {
console.log(this.name);
}.bind(this))
}
}
p.getName();
2 通过设置其他的参数that保留
let p = {
name: "Aeroxian",
getName: function () {
// 需要改变this指向
let that = this;
// 异步代码
setTimeout(function () {
console.log(that.name);
})
}
}
p.getName();
1.2.2 箭头函数this为外层this
- 对于有异步代码要处理this,箭头函数非常方便
let p = {
name: "Aeroxian",
getName: function () {
// 箭头函数的this为外层的this,即p实例
// 异步代码
setTimeout(() => {
console.log(this.name);
})
}
}
p.getName();
1.3 匿名函数(函数表达式)
// 在nodejs中vm用于执行代码生成这样一个函数
let fn = (function(){});
fn();
1.4 立即执行函数
(function(){})();
2 函数参数
2.1 函数内置对象arguments
接收所有的实参
2.1.1 属性
1 length实参个数
2 callee当前函数
整个函数,而不是一个函数名
typeof arguments.callee // function
2.1.2 数组使用arguments[]
通过遍历arguments能够获取到实参
for (let i = 0; i < arguments.length; i++) {
arguments[i]
}
2.2 函数名.length形参个数
表示函数形参个数
2.3 函数名.name函数的名称
2.3 默认参数
function name(name="Aeroxian",school="CAU"){}
2.4 剩余运算符
function fn(param, ...num) {
console.log(param, num);
}
// 1 [2,3]
fn(1, 2, 3)
3 改变函数this指向
3.1 call,apply 都可以改变this指向
call传递数字逗号分割
functionName.call(this,arges)apply传递数组
3.2 bind 改变函数this指向,但不会执行
let newFn = fn.bind(obj)
let btn = document.querySelector("input[type=button]")
btn.onclick = function () {
// bind方法
setInterval(function () {
// setInterval默认this为window
console.log(this);
}.bind(this), 1000);
}
用that保存this
let btn = document.querySelector("input[type=button]") btn.onclick = function () { let that = this; setInterval(function () { // setInterval默认this为window console.log(that); }, 1000); }箭头函数的this与所处的代码有关
4 高阶函数
4.1 函数的参数为函数
- callback回调函数
4.2 返回值是函数
- 闭包
function type(variable){
return Object.prototype.toString.call(variable);
}
